<template>
    <div style="background: white">
        <div style="margin-top: 30px;margin-left: 100px;">
            <div style="width: 1240px;margin: 30px">
                <div>
                    <a-row style="padding-top: 36px">
                        <a-col :span="20"></a-col>
                        <a-col :span="4">
                            已选商品：<span class="totalPrice">￥{{totalPrice}} 元</span>
                        </a-col>
                    </a-row>
                </div>
            </div>
            <vxe-table
                    ref="xTable"
                    height="1000"
                    align="center"
                    auto-resize
                    style="width: 1240px"
                    :tree-config="{expandAll:true,iconOpen:'fa fa-shopping-bag',iconClose:'fa fa-shopping-bag'}"
                    @checkbox-all="selectAllEvent"
                    :checkbox-config="{ checkMethod: checkMethod}"
                    @checkbox-change="selectChangeEvent"
                    :data="tableData">
                <vxe-table-column type="checkbox" width="60"></vxe-table-column>

                <vxe-table-column field="name" title="商品" width="300" tree-node>
                    <template v-slot="{row}">
                        <div class="goodsName">
                            <a style="color:#3c3c3c;" @click="toDetail(row)">
                                {{row.name}}
                            </a>
                        </div>

                    </template>
                </vxe-table-column>

                <vxe-table-column field="picture" title="图片" width="120">
                    <template v-slot="{ row }">
                        <a @click="toDetail(row)"><img v-if="row.picture" :src="row.picture" style="width: 100px;"></a>
                    </template>
                </vxe-table-column>
                <vxe-table-column field="specStr" title="规格" width="200">
                    <template v-slot="{row}">

                        <!--优惠券-->
                        <a-dropdown :trigger="['click']"
                                    v-if="Object.prototype.toString.call(row.specStr) == '[object Array]'&&row.specStr.length>0">
                            <div style="border: 1px solid #F9D2D3;width: 100px;border-radius: 10px">
                                <a style="color: #E4393C" @click="e => e.preventDefault()">
                                    优惠券
                                    <a-icon type="down"/>
                                </a>
                            </div>
                            <a-menu slot="overlay">
                                <coupon-card :coupon-data="row.specStr" :shop-name="row.name"
                                            ></coupon-card>
                            </a-menu>
                        </a-dropdown>
                        <span v-if="Object.prototype.toString.call(row.specStr) !== '[object Array]'" class="specStr">{{row.specStr}}</span>
                    </template>
                </vxe-table-column>

                <vxe-table-column field="price" title="单价" width="140">
                    <template v-slot="{row}">
                    <span class="price">
                        <span v-if="row.price">￥</span>
                        <span>{{row.price?(row.price+'').indexOf(".")>-1?row.price:row.price+'.00':''}}</span>
                    </span>
                    </template>
                </vxe-table-column>
                <vxe-table-column field="num" title="数量" width="120">
                    <template v-slot="{row}">
                        <a-input-number v-if="row.num" :min="1" v-model="row.num"
                                        @change="value=>changeNum(row,value)"></a-input-number>
                    </template>
                </vxe-table-column>
                <vxe-table-column field="totalPrice" title="金额" width="140">
                    <template v-slot="{row}">
                    <span class="totalPrice">
                        <span v-if="row.totalPrice">￥</span>
                        <span>{{row.totalPrice?(row.totalPrice+'').indexOf(".")>-1?row.totalPrice:row.totalPrice+'.00':''}}</span>

                    </span>
                    </template>
                </vxe-table-column>
                <vxe-table-column title="操作" width="160">
                    <template v-slot="{ row }">

                        <template v-if="row.picture">
                            <div class="oper-div">
                                <a class="oper-btn" @click="addCollect(row)">移入收藏</a>
                            </div>
                            <div class="oper-div">
                                <a-popconfirm
                                        title="确定将该宝贝从购物车删除吗?"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="deleteBatch(row.id,row.skuId)"
                                        @cancel="()=>{}"
                                >
                                    <a class="oper-btn">删 除</a>
                                </a-popconfirm>
                            </div>
                        </template>
                    </template>
                </vxe-table-column>
            </vxe-table>

            <div class="bottom-commit">
                <div style="margin-right: 5px" class="shopping-car-div">
                    <a-row>
                        <a-col :span="3">
                            <a-checkbox :checked="checkedAll" @change="toggleAllCheckboxRow">全选</a-checkbox>
                        </a-col>
                        <a-col :span="2">
                            <div class="oper-div">
                                <a-popconfirm
                                        title="确定删除选中的宝贝吗？"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="deleteBatch(null,null)"
                                        @cancel="()=>{}"
                                >
                                    <a class="bottom-menu">删除选中的宝贝</a>
                                </a-popconfirm>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="loginFlag">
                            <div class="oper-div">
                                <a-popconfirm
                                        title="确定清除所有失效的宝贝吗？"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="deleteInvalid"
                                        @cancel="()=>{}"
                                >
                                    <a class="bottom-menu">清除失效宝贝</a>
                                </a-popconfirm>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="oper-div">
                                <a class="bottom-menu" @click="addCollect(null)">移入收藏夹</a>
                            </div>
                        </a-col>
                        <a-col :span="3"></a-col>
                        <a-col :span="3">
                            <span class="bottom-text">已选择 {{selectedSkus.length}} 件商品</span>
                        </a-col>
                        <a-col :span="3">
                            <span>
                                <span class="bottom-text">
                                    合计：
                                </span>
                                <span class="bottom-totalPrice">￥{{totalPrice}} 元</span>
                            </span>
                        </a-col>
                        <a-col :span="3">
                            <span class="add-shopping-cart" @click="confirmOrder">结  算</span>

                        </a-col>
                    </a-row>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
    import XEUtils from 'xe-utils'
    import cartApi from "../../api/goods/cartApi";
    import collectApi from "../../api/info/collectApi";
    import Cookies from "js-cookie";
    import {isArr} from "../../utils/arrayUtil"
    import {getLocalStorageJson, setLocalStorageJson} from "../../utils/auth";
    import CouponCard from "../../components/goods/coupon/CouponCard";
    import couponApi from "../../api/info/couponApi";

    export default {
        name: "cartIndex",
        components: {CouponCard},
        inject: ["reload"],
        data() {
            return {
                tableData: [],
                selectedSkus: [],
                checkedAll: false,//是否全选 底部全选复选框控制
                skuCount: 0,//购物车商品总量
                totalPrice: 0.00//选中的商品总金额
            }
        },
        created() {
            this.loadGroup()
        },
        methods: {

            confirmOrder() {
                if (this.selectedSkus.length <= 0) {
                    this.$message.warning("请先选择商品");
                    return;
                } else {
                    let carIds = this.selectedSkus.map(car => car.id)
                    this.$router.push(`/confirm_order?ids=${carIds}`)
                }
            },
            loadGroup() {

                const token = Cookies.get("user_token_web");
                this.loginFlag = token
                if (token) {
                    cartApi.shoppingData().then(resp => {
                        if (resp.data.flag) {
                            console.log(resp.data.data)
                            this.tableData = resp.data.data;
                            let skuCount = 0;
                            this.tableData.forEach(item => {
                                let temp = item.children.filter(sku => sku.valid === true)
                                skuCount += temp.length;
                            })
                            this.skuCount = skuCount;

                        }
                    })
                } else {
                    let cartList = getLocalStorageJson("mm_cart");
                    let shopGroup = []
                    if (cartList && cartList.length > 0) {
                        cartList.forEach(cart => {

                            let target = shopGroup.find(item => item.shopId === cart.shopId);
                            if (target) {
                                target.children.push(cart)
                            } else {

                                let shopGoods = {
                                    shopId: cart.shopId,
                                    name: '店铺：' + cart.shopName,
                                    latestTime: undefined,
                                    // specStr: [{id: 1, name: "满"}],
                                    children: [cart]
                                }
                                shopGroup.push(shopGoods)
                            }
                        })
                        let skuCount = 0;
                        shopGroup.forEach(item => {
                            let latestTime = item.children[0].modifyTime;
                            skuCount += item.children.length
                            item.children.forEach(sku => {
                                sku.valid = true
                                if (sku.modifyTime > latestTime) {
                                    latestTime = sku.modifyTime;
                                }
                            })
                            item.latestTime = latestTime;
                        })
                        this.skuCount = skuCount;
                        shopGroup.sort((x, y) => x.latestTime > y.latestTime)
                        console.log(shopGroup)
                        this.tableData = shopGroup
                    }
                }


            },


            /**
             * 移入收藏
             */
            addCollect(row) {
                let that = this
                this.$confirm({
                    title: '确定移出到收藏吗？移入到收藏后则会将宝贝从购物车移除',
                    onOk() {
                        if (row) {
                            let collect = {
                                targetId: row.goodsId,
                                type: 1
                            }
                            collectApi.add([collect]).then(resp => {
                                if (resp.data.flag) {
                                    cartApi.deleteGoodsBatch([row.id]).then(resp => {
                                        if (resp.data.flag) {
                                            that.$message.success("ok")
                                            that.reload()
                                        }
                                    })
                                }
                            })
                        } else {
                            if (that.selectedSkus.length <= 0) {
                                that.$message.warning("请先选择商品")
                                return;
                            }
                            let collectList = []
                            let carIds = []
                            that.selectedSkus.forEach(item => {
                                collectList.push({
                                    targetId: item.goodsId,
                                    type: 1
                                })
                                carIds.push(item.id)
                            })
                            collectApi.add(collectList).then(resp => {
                                if (resp.data.flag) {
                                    cartApi.deleteGoodsBatch(carIds).then(resp => {
                                        if (resp.data.flag) {
                                            that.$message.success("ok")
                                            that.reload()
                                        }
                                    })
                                }
                            })
                        }
                    },
                    onCancel() {
                    },
                });
            },
            /**
             * 清除所有失效宝贝
             */
            deleteInvalid() {
                cartApi.deleteInvalid().then(resp => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message)
                        this.reload()
                    }
                })
            }
            ,


            /**
             * 批量删除商品
             * @param id
             * @param skuId 离线删除使用
             */
            deleteBatch(id, skuId) {
                const token = Cookies.get("user_token_web");
                let delIds = []
                console.log(skuId)
                if (token){
                    //在线
                    if (id) {
                        //在线单个删除
                        delIds =[id]
                    } else {
                        //批量删除
                        delIds = this.selectedSkus.length > 0 ? this.selectedSkus.map(item => item.id) : []
                    }
                }else{
                    //离线
                    if (skuId){
                        delIds =[skuId]
                    }else {
                        //离线批量
                        delIds = this.selectedSkus.length > 0 ? this.selectedSkus.map(item => item.skuId) : []
                    }
                }
                if (delIds.length <= 0) {
                    this.$message.warning("您尚未选择任何商品");

                }
                if (token) {
                    cartApi.deleteGoodsBatch(delIds).then(resp => {
                        if (resp.data.flag) {
                            this.$message.success(resp.data.message)
                            this.reload()
                        }
                    })
                } else {
                    let cartList = getLocalStorageJson("mm_cart");
                    if (cartList && cartList.length > 0) {
                        cartList=cartList.filter(cart=>!delIds.includes(cart.skuId))
                        setLocalStorageJson("mm_cart",cartList)
                        this.reload()
                    }
                }

            }
            ,
            changeNum(row, value) {
                let targetShopGroup = this.tableData.find(item => item.shopId === row.shopId);
                if (targetShopGroup) {
                    let targetSku = targetShopGroup.children.find(item => item.skuId === row.skuId);

                    if (targetSku) {
                        if (this.loginFlag) {
                            //登录了
                            console.log(targetSku)
                            let totalPrice = value * targetSku.price
                            cartApi.updateNum(targetSku.id, value, totalPrice).then(resp => {
                                if (resp.data.flag) {
                                    this.reload()
                                }
                            })

                        } else {
                            targetSku.num = value;
                            targetSku.totalPrice = (targetSku.num * targetSku.price).toFixed(2)
                            let newCart = []
                            this.tableData.forEach(item => {
                                item.children.forEach(sku => {
                                    newCart.push(sku)
                                })
                            })
                            setLocalStorageJson("mm_cart", newCart)
                        }

                        console.log(this.tableData)
                    }
                }

            }
            ,

            /**
             * 确定哪些行不可以复选
             * 商品无效不可以选择
             * 店铺下的所有商品都无效则该店铺不可选择
             */
            checkMethod({row}) {
                if (row.children) {
                    //店铺行
                    for (let i = 0; i < row.children.length; i++) {
                        if (row.children[i].valid === true) {
                            return true;
                        }
                    }
                    return false;
                } else {
                    return row.valid === true;
                }
            },
            /**
             * 全选
             */
            toggleAllCheckboxRow(e) {
                console.log(e)
                this.checkedAll = e.target.checked;
                this.$refs.xTable.toggleAllCheckboxRow()
            },
            refreshTotalPrice() {
                this.totalPrice = 0.00
                console.log(this.selectedSkus)
                this.selectedSkus.forEach(sku => this.totalPrice += sku.totalPrice)
            },
            /**
             * 全选/全不选 事件
             */
            selectAllEvent({checked, records}) {
                this.checkedAll = checked
                let skus = records.filter(item => !item.children)
                this.selectedSkus = skus;
                this.refreshTotalPrice();

            },
            /**
             * 选择/取消一个事件
             */
            selectChangeEvent({checked, records}) {

                console.log(records)
                let skus = records.filter(item => !item.children)
                console.log(skus)
                skus.length === this.skuCount ? this.checkedAll = true : this.checkedAll = false;
                console.log(skus.length)
                console.log(this.skuCount)

                this.selectedSkus = skus
                this.refreshTotalPrice();
            }
            ,
            /**
             * 到详情页
             */
            toDetail(row) {
                let selectedParam = JSON.parse(row.selectedParam)
                let indexesArr = Object.values(selectedParam)
                let indexes = ""
                indexesArr.forEach(item => {
                    indexes += item + "_"
                })
                let uri = `/goodDetail?goodsInfo=${encodeURI(JSON.stringify({
                    id: row.goodsId,
                    index: indexes.substring(0, indexes.length - 1)
                }))}`
                this.$router.push(encodeURI(uri))
            },
        }
    }
</script>

<style scoped>

</style>
<style>

    .vxe-tree--node-btn {
        color: #E4393C;
        margin-top: 10px;
        font-size: 16px;
    }

    .vxe-tree--btn-wrapper {
        color: #E4393C;
    }

    .vxe-header--row {
        background: white;
    }

    .price {
        color: #3C3D3C;
        font-weight: 700;
    }

    .totalPrice {
        color: #FF4400;
        font-weight: 700;
    }

    .goodsName {
        font-size: 13px;
        float: left;
    }

    .goodsName :hover {
        color: #E2231A;
    }

    .specStr {
        color: #9c9c9c;
        font-size: 12px;
    }

    .oper-btn {
        color: #868686;
    }

    .oper-div :hover {
        color: #E4393C;
    }

    .bottom-menu {
        font-size: 12px;
        color: #868686;
    }

    .bottom-menu :hover {
        color: #E4393C;
    }

    .bottom-commit {
        position: fixed;
        height: 72px;
        width: 1240px;
        bottom: 0px;
        text-align: center;
        border-top: #E4393C solid 2px;
        background: white;
    }

    .add-shopping-cart {
        background: #DE3033;
        padding: 14px 20px;
        color: white;
        font-size: 18px;
        font-family: "microsoft yahei";
        height: 36px;

    }

    .shopping-car-div {
        height: 42px;
        margin-top: 22px;
    }

    .shopping-car-div :hover {
        cursor: pointer;

    }

    .bottom-totalPrice {
        font-size: 16px;
        font-weight: 700;
        font-family: Verdana;
        color: #E2231A;
    }

    .bottom-text {
        font-size: 13px;
        color: #999;

    }


</style>
